using Digitalmes.Domain.Entities.Mes.Productions;

namespace Digitalmes.Application.Mes.Productions.Products.Queries;

/// <summary>
/// 分页查询产品信息命令。
/// </summary>
public sealed record GetProductListWithPagedQuery(
    string? Sn,
    long? ProductId,
    string? Wo,
    int PageNumber,
    int PageSize) : IPagedQuery, IRequest<IResult<PagedList<ProdCurrentStateDto>>>;

internal sealed class GetProductListWithPagedQueryHandler(IRepository<ProdCurrentState> repo) : IRequestHandler<GetProductListWithPagedQuery, IResult<PagedList<ProdCurrentStateDto>>>
{
    public async Task<IResult<PagedList<ProdCurrentStateDto>>> Handle(GetProductListWithPagedQuery request, CancellationToken cancellationToken)
    {
        var items = await repo.AsQueryable()
            .WhereIF(!string.IsNullOrEmpty(request.Sn), m => m.Sn.Contains(request.Sn!))
            .WhereIF(request.ProductId != null, m => m.ProductId == request.ProductId)
            .WhereIF(!string.IsNullOrEmpty(request.Wo), m => m.Wo == request.Wo)
            .GetPagedListAsync(request.PageNumber, request.PageSize, cancellationToken);
        return Result.From(items.Adapt<PagedList<ProdCurrentStateDto>>());
    }
}
